import { UserManager } from 'oidc-client'
import { createLocalStorage } from '../cache'
let oidcManager = null

export const initServe = () => {
  if (oidcManager) return oidcManager
  const { VITE_APP_AUTHORITY, VITE_APP_CLIENT_ID, VITE_APP_CLIENT_SECRET } = import.meta.env
  console.log('配置', import.meta.env)
  oidcManager = new UserManager({
    /* 认证服务器 */
    authority: VITE_APP_AUTHORITY,
    /* 客户端id */
    client_id: VITE_APP_CLIENT_ID,
    client_secret: VITE_APP_CLIENT_SECRET,
    /* 回调客户端页面 */
    redirect_uri: `${window.location.origin}/login`,
    post_logout_redirect_uri: `${window.location.origin}/login`,
    response_type: 'code',
    /* 授权范围  */
    scope: 'openid profile',
    automaticSilentRenew: true,
    revokeAccessTokenOnSignout: true,
    metadata: {
      issuer: `${VITE_APP_AUTHORITY}`,
      authorization_endpoint: `${VITE_APP_AUTHORITY}/oauth2/authorize`,
      token_endpoint: `${VITE_APP_AUTHORITY}/oauth2/token`,
      userinfo_endpoint: `${VITE_APP_AUTHORITY}/userinfo`,
      end_session_endpoint: `${VITE_APP_AUTHORITY}/toLogout`,
      revocation_endpoint: `${VITE_APP_AUTHORITY}/oauth2/revoke`
    }
  })
  return oidcManager
}

export const getUserInfo = async () => {
  oidcManager = initServe()
  return await oidcManager.getUser()
}
/* 登录 */
export const signinRedirect = async () => {
  oidcManager = initServe()
  oidcManager
    .signinRedirect({})
    .then((res) => {
      setPath(window.location.pathname)
      console.log('signed in', res)
    })
    .catch((err) => {
      console.err(err)
    })
}
/* 登录回调 */
export const signinRedirectCallback = async () => {
  const userInfo = await getUserInfo()
  if (!userInfo) {
    oidcManager = initServe()
    return await oidcManager.signinRedirectCallback()
  }
}
/* 退出 */
export const signoutRedirect = () => {
  oidcManager = initServe()
  oidcManager
    .signoutRedirect({})
    .then(function (res) {
      setPath(window.location.pathname)
      console.log('signed out', res)
    })
    .catch(function (err) {
      console.log(err)
    })
}
/* 退出回调 */
export const signoutRedirectCallback = async () => {
  const userInfo = await getUserInfo()
  if (!userInfo) {
    oidcManager = initServe()
    return await oidcManager.signoutRedirectCallback()
  }
}

const PATH_CODE = 'redirect_path'
const DURATION = 24 * 60 * 60
export const isPath = createLocalStorage()
// export const isPath = false
/* 获取Path */
export function getPath() {
  return isPath.get(PATH_CODE)
}
/* 设置Path */
export function setPath(Path, duration = DURATION) {
  isPath.set(PATH_CODE, Path, duration)
}
/* 移出Path */
export function removePath() {
  isPath.remove(PATH_CODE)
}
